import 'dart:math';
import 'package:extended_image/extended_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_rider/main/widgets/ext/u_title_layout.dart';
import 'package:flutter_rider/main/widgets/ui_constant.dart';
import 'package:flutter_rider/main/models/waybill_record_model.dart';
import 'package:flutter_rider/utils/calculate_utils.dart';
import 'package:flutter_rider/utils/convert.dart';
import 'package:flutter_rider/utils/screen_fit.dart';
import '../../../utils/log.dart';

class ImageViewerPage extends StatefulWidget {
  List<dynamic> images;
  int index;
  WaybillRecordModel? record;
  ImageViewerPage(this.images, {this.record, Key? key, this.index = 0})
      : super(key: key);

  @override
  State createState() => _ImageViewerPageState();
}

class _ImageViewerPageState extends State<ImageViewerPage>
    with TickerProviderStateMixin {
  late AnimationController _doubleClickAnimationController;
  late VoidCallback _doubleClickAnimationListener;
  Animation<double>? _doubleClickAnimation;
  List<double> doubleTapScales = <double>[1.0, 2.0];
  bool _showAppBar = true;

  @override
  void initState() {
    super.initState();
    _doubleClickAnimationController = AnimationController(
        duration: const Duration(milliseconds: 150), vsync: this);
  }

  @override
  void dispose() {
    _doubleClickAnimationController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    var height = 44.rpx + MediaQuery.of(context).padding.top;
    return Material(
      color: Colors.black,
      child: Stack(
        children: [
          SafeArea(child: _renderPageViewer()),
          AnimatedPositionedDirectional(
            duration: kThemeAnimationDuration,
            top: _showAppBar ? 0 : -height,
            start: 0,
            end: 0,
            height: height,
            child: SizedBox(
              height: height,
              child: UTitleLayout.getBackTitle(
                  context, "${widget.index + 1}/${widget.images.length}"),
            ),
          ),
        ],
      ),
    );
  }

  double? initScale(
      {required Size imageSize, required Size size, double? initialScale}) {
    final double n1 = imageSize.height / imageSize.width;
    final double n2 = size.height / size.width;
    if (n1 > n2) {
      final FittedSizes fittedSizes =
          applyBoxFit(BoxFit.contain, imageSize, size);
      //final Size sourceSize = fittedSizes.source;
      final Size destinationSize = fittedSizes.destination;
      return size.width / destinationSize.width;
    } else if (n1 / n2 < 1 / 4) {
      final FittedSizes fittedSizes =
          applyBoxFit(BoxFit.contain, imageSize, size);
      //final Size sourceSize = fittedSizes.source;
      final Size destinationSize = fittedSizes.destination;
      return size.height / destinationSize.height;
    }
    Log.i("scale = $initialScale");
    return initialScale;
  }

  Widget _renderPageViewer() {
    final Size size = MediaQuery.of(context).size;
    return ExtendedImageGesturePageView.builder(
      controller: ExtendedPageController(
        initialPage: widget.index,
      ),
      itemBuilder: (context, index) {
        var item = widget.images[index];
        Widget image = ExtendedImage.network(
          item,
          fit: BoxFit.contain,
          mode: ExtendedImageMode.gesture,
          initGestureConfigHandler: (state) {
            double? initialScale = 1;

            if (state.extendedImageInfo != null) {
              initialScale = initScale(
                  size: size,
                  initialScale: initialScale,
                  imageSize: Size(
                      state.extendedImageInfo!.image.width.toDouble(),
                      state.extendedImageInfo!.image.height.toDouble()));
            }
            return GestureConfig(
              inPageView: true,
              initialScale: initialScale!,
              maxScale: max(initialScale, 5.0),
              animationMaxScale: max(initialScale, 5.0),
              initialAlignment: InitialAlignment.center,
              //you can cache gesture state even though page view page change.
              //remember call clearGestureDetailsCache() method at the right time.(for example,this page dispose)
              cacheGesture: false,
            );
          },
          onDoubleTap: _onDoubleTap,
        );
        return GestureDetector(
          onTap: () {
            setState(() {
              _showAppBar = !_showAppBar;
            });
          },
          child: Stack(
              alignment: Alignment.center, children: [image, addWatermark()]),
        );
      },
      itemCount: widget.images.length,
      onPageChanged: (index) {
        widget.index = index;
        setState(() {});
      },
    );
  }

  _onDoubleTap(ExtendedImageGestureState state) {
    final Offset? pointerDownPosition = state.pointerDownPosition;
    final double? begin = state.gestureDetails!.totalScale;
    double end;

    //remove old
    _doubleClickAnimation?.removeListener(_doubleClickAnimationListener);

    //stop pre
    _doubleClickAnimationController.stop();

    //reset to use
    _doubleClickAnimationController.reset();

    if (begin == doubleTapScales[0]) {
      end = doubleTapScales[1];
    } else {
      end = doubleTapScales[0];
    }

    _doubleClickAnimationListener = () {
      //print(_animation.value);
      state.handleDoubleTap(
          scale: _doubleClickAnimation!.value,
          doubleTapPosition: pointerDownPosition);
    };
    _doubleClickAnimation = _doubleClickAnimationController
        .drive(Tween<double>(begin: begin, end: end));

    _doubleClickAnimation!.addListener(_doubleClickAnimationListener);

    _doubleClickAnimationController.forward();
  }

  Widget addWatermark() {
    var record = widget.record;
    if (record == null) return 0.wspace;
    if (record.address.isEmpty) return 0.wspace;
    double time = record.created_time_stamp / 1000;
    var dateTime = DateTime.fromMicrosecondsSinceEpoch(time.toInt());
    var weekDay = Convert.toDayWeek(dateTime);

    ///右下角的水印部分
    return Positioned(
        left: 17.rpx,
        bottom: 32.rpx,
        child: IntrinsicHeight(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                // mainAxisAlignment: MainAxisAlignment.end,
                // crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Padding(
                    padding: EdgeInsets.only(
                        left: 0, right: 8.rpx, top: 0, bottom: 0),
                    child: Text(
                      "${dateTime.hour.toString().padLeft(2, '0')}:${dateTime.minute.toString().padLeft(2, '0')}",
                      style: TextStyle(
                          fontSize: 40.rpx,
                          color: Colors.white,
                          shadows: [
                            Shadow(
                              color: UIColor.color_shadow,
                              offset: const Offset(1, 1),
                            )
                          ]),
                    ),
                  ),
                  Container(
                    width: 3.rpx,
                    height: 40.rpx,
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(2),
                      boxShadow: [
                        BoxShadow(
                          color: UIColor.color_shadow,
                          offset: Offset(1, 1), //阴影y轴偏移量
                          blurRadius: 0, //阴影模糊程度
                          // spreadRadius: 0 //阴影扩散程度
                        )
                      ],
                    ),
                  ),
                  Container(
                    height: 40.rpx,
                    child: Column(
                      // mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Padding(
                          padding: EdgeInsets.only(
                              left: 8.rpx, right: 8.rpx, top: 0, bottom: 0),
                          child: Text(
                            "${dateTime.year}-${dateTime.month.toString().padLeft(2, '0')}-${dateTime.day.toString().padLeft(2, '0')}",
                            style: TextStyle(
                                fontSize: 14.rpx,
                                color: Colors.white,
                                shadows: [
                                  Shadow(
                                    color: UIColor.color_shadow,
                                    offset: const Offset(1, 1),
                                  )
                                ]),
                          ),
                        ),
                        const Spacer(),
                        Container(
                          alignment: Alignment.centerLeft,
                          padding: EdgeInsets.only(
                              left: 8, right: 8.rpx, top: 0, bottom: 0),
                          child: Text(
                            weekDay,
                            style: TextStyle(
                                fontSize: 14.rpx,
                                color: Colors.white,
                                shadows: [
                                  Shadow(
                                    color: UIColor.color_shadow,
                                    offset: const Offset(1, 1),
                                  )
                                ]),
                          ),
                        ),
                      ],
                    ),
                  )
                ],
                // padding: EdgeInsets.only(left: 0,right: 17,top: 8,bottom: 0),
                // decoration:
                // BoxDecoration(border: Border.all(
                //     color: Colors.red,
                //     width: 1.0
                // )),
              ),
              12.hspace,
              Container(
                //              constraints: BoxConstraints(
                // maxHeight: 45.0,
                // maxWidth: MediaQuery.of(context).size.width - 17.rpx - 17.rpx,
                // minHeight: 45.0,
                // minWidth: MediaQuery.of(context).size.width - 17.rpx - 17.rpx),
                // height: 45.rpx,
                height: Calculate.calculateTextHeight(
                    record.address,
                    14.rpx,
                    FontWeight.normal,
                    MediaQuery.of(context).size.width - 34.rpx,
                    2),
                width: MediaQuery.of(context).size.width - 34.rpx,
                // padding: EdgeInsets.only(
                // left: 0, right: 0.rpx, top: 0.rpx, bottom: 0),
                // decoration:
                // BoxDecoration(border: Border.all(
                //     color: Colors.red,
                //     width: 1.0
                // )),
                child: Text(
                  record.address,
                  overflow: TextOverflow.ellipsis,
                  maxLines: 2,
                  style: TextStyle(
                      fontSize: 14.rpx,
                      color: Colors.white,
                      shadows: [
                        Shadow(
                          color: UIColor.color_shadow,
                          offset: const Offset(1, 1),
                        )
                      ]),
                ),
              ),
              Padding(
                padding: EdgeInsets.only(
                    left: 0, right: 17.rpx, top: 8.rpx, bottom: 0),
                // decoration:
                // BoxDecoration(border: Border.all(
                //     color: Colors.red,
                //     width: 1.0
                // )),
                child: Text(
                  "东经：${record.lng} 北纬：${record.lat}",
                  style: TextStyle(
                      fontSize: 14.rpx,
                      color: Colors.white,
                      shadows: [
                        Shadow(
                          color: UIColor.color_shadow,
                          offset: const Offset(1, 1),
                        )
                      ]),
                ),
              ),
            ],
          ),
        ));
  }
}
